package com.fc.im.netty.util;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;

/**
 * Created by ChanJiabo on 2017/1/17.
 */
public class ChannelUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChannelUtil.class);

    /**
     * 解析地址
     *
     * @param channel
     * @return
     */
    public static String parseChannelRemoteAddr(final Channel channel) {
        if (null == channel) {
            return "";
        }

        final SocketAddress remote = channel.remoteAddress();
        final String addr = remote != null ? remote.toString() : "";

        if (addr.length() > 0) {
            int index = addr.lastIndexOf("/");
            if (index > 0) {
                return addr.substring(index + 1);
            }
            return addr;
        }
        return "";

    }

    public static void closeChannel(Channel channel) {
        final String addrRemote = parseChannelRemoteAddr(channel);
        channel.close().addListener(new ChannelFutureListener() {

            public void operationComplete(ChannelFuture future) throws Exception {
                LOGGER.info("closeChannel : close the connection to remote address[{}]" +
                        " result:[{}]", addrRemote, future.isSuccess());
            }
        });

    }
}
